package com.xinghai.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.xinghai.admin.domain.SysConfig;
import com.xinghai.admin.service.ISysConfigService;
import com.xinghai.common.constant.Constants;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.PageUtils;
import com.xinghai.common.utils.uuid.IdUtils;
import com.xinghai.domain.JkqActivity;
import com.xinghai.domain.JkqActivityAddress;
import com.xinghai.domain.JkqActivityLog;
import com.xinghai.domain.JkqUser;
import com.xinghai.service.*;
import com.xinghai.wechat.WeChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api")
public class ApiController extends BaseController {

    @Autowired
    private WxMaService maService;

    @Autowired
    private IJkqUserService userService;

    @Autowired
    private IJkqActivityService jkqActivityService;

    @Autowired
    private IJkqActivityAddressService jkqActivityAddressService;

    @Autowired
    private IJkqActivityShareService shareService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IJkqActivityLogService activityLogService;

    /**
     * 微信登录
     * @param code
     * @return
     */
    @GetMapping("/wxLogin")
    public AjaxResult wxLogin(String code,Long yqUserId) {
        try {
            WxMaJscode2SessionResult wxMaJscode2SessionResult = maService.jsCode2SessionInfo(code);
            System.out.println(JSONObject.toJSONString(wxMaJscode2SessionResult));
//            String wxInfo = WeChatService.getOpenId(code);
//            System.out.println(wxInfo);
            String openid = wxMaJscode2SessionResult.getOpenid();
            JkqUser user = userService.getInfoByOpenId(openid);
            boolean flag = false;
            if (user == null){
                JkqUser jkqUser = new JkqUser();
                jkqUser.setOpenId(openid);
                jkqUser.setNickname("用户"+ IdUtils.randomNanoId()+(yqUserId!=null?yqUserId:""));
                jkqUser.setImageUrl("/profile/avatar/2025/08/14/9c85d3a5641b45d6b27bce17a70c5541.png");
                jkqUser.setLoginNum(1);
                jkqUser.setLastLoginTime(DateUtils.getNowDate());
                //绑定邀请人的健康管理师id
                if (yqUserId != null){
                    JkqUser user1 = userService.getById(yqUserId);
                    if (user1 != null){
                        jkqUser.setYqUserId(yqUserId);
                        if (user1.getHealthUserId()!=null){
                            jkqUser.setHealthUserId(user1.getHealthUserId());
                        }
                    }
                }
                boolean save = userService.save(jkqUser);
                if (!save){
                    return error("登录失败");
                }
                flag = true;
                StpUtil.login(jkqUser.getId());
            }else {
                if (user.getStatus().equals("1")){
                    return error("该账号被禁用");
                }
                if (yqUserId != null&&(user.getYqUserId() == null||user.getHealthUserId() == null)){
                    JkqUser user1 = userService.getById(yqUserId);
                    if (user1 != null){
                        if (user.getYqUserId()==null){
                            user.setYqUserId(yqUserId);
                        }
                        //绑定邀请人的健康管理师id
                        if (user.getHealthUserId() == null&&user1.getHealthUserId()!=null){
                            user.setHealthUserId(user1.getHealthUserId());
                        }
                        userService.updateById(user);
                    }
                }
                StpUtil.login(user.getId());
            }
            String token = StpUtil.getTokenInfo().getTokenValue();
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            ajax.put("flag", flag);
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return error("登录失败");
        }
    }

    /**
     * 获取活动列表
     * @return
     */
    @GetMapping("/getActivityList")
    public AjaxResult getActivityList() {
        startPage();
        PageUtils.orderBy("create_time desc");
        JkqActivity jkqActivity = new JkqActivity();
        jkqActivity.setStatus("0");
        return success(getDataTable(jkqActivityService.list(jkqActivity)));
    }


    /**
     * 获取活动记录列表
     * @return
     */
    @GetMapping("/getLogList")
    public AjaxResult getLogList(Long activityId) {
        startPage();
        PageUtils.orderBy("create_time desc");
        JkqActivityLog jkqActivityLog = new JkqActivityLog();
        jkqActivityLog.setActivityId(activityId);
        jkqActivityLog.setStatus("0");
        return success(getDataTable(activityLogService.list(jkqActivityLog)));
    }

    /**
     * 获取活动列表
     * @return
     */
    @PostMapping("/logout")
    public AjaxResult logout() {
        try {
            StpUtil.logout();
        }catch (Exception e){
            return success();
        }
        return success();
    }


    /**
     * 获取活动列表
     * @return
     */
    @GetMapping("/shareGet")
    public AjaxResult shareGet(Long activityId,Long userId) {
        shareService.updateShareNumByActivityId(activityId,userId);
        return success();
    }


    /**
     * 获取活动详情
     * @param id
     * @return
     */
    @GetMapping("/getActivityInfo")
    public AjaxResult getActivityInfo(String id) {
        return success(jkqActivityService.getById(id));
    }


    /**
     * 获取活动详情
     * @param id
     * @return
     */
    @GetMapping("/getActivityAddress")
    public AjaxResult getActivityAddress(Long id) {
        JkqActivityAddress jkqActivityAddress = new JkqActivityAddress();
        jkqActivityAddress.setActivityId( id);
        jkqActivityAddress.setStatus("0");
        return success(jkqActivityAddressService.list(jkqActivityAddress));
    }


    /**
     * 获取配置信息
     * @return
     */
    @GetMapping("/getConfigInfo")
    public AjaxResult getConfigInfo() {
        String phone = sysConfigService.selectConfigByKey("sys.wx.phone");
        String workTime = sysConfigService.selectConfigByKey("sys.wx.workTime");
        String email = sysConfigService.selectConfigByKey("sys.wx.email");
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("workTime", workTime);
        map.put("email", email);
        return success(map);
    }

}
